package com.mm.cloth.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.mm.cloth.R;
import com.mm.cloth.view.WatermarkRemovalCanvasView;
import com.mm.cloth.utils.WatermarkRemovalAPI;
import com.mm.cloth.rmbg.LamaWatermarkProcessor;
import com.mm.cloth.rmbg.WatermarkRemovalProcessor;
import com.mm.cloth.rmbg.WatermarkRemovalTFLiteProcessor;

import java.io.IOException;
import java.io.InputStream;

public class WatermarkRemovalActivity extends AppCompatActivity {
    private static final String TAG = "WatermarkRemovalActivity";
    private static final int REQUEST_IMAGE_PICK = 1001;
    private static final int REQUEST_PERMISSION = 1002;
    
    private WatermarkRemovalCanvasView watermarkCanvas;
    private com.mm.cloth.view.SlideCompareView slideCompareView;
    private LinearLayout uploadArea;
    private LinearLayout progressOverlay;
    private TextView tvProgress;
    private TextView tvProgressDetail;
    private Button btnUndo;
    private Button btnRedo;
    private Button btnClear;
    private Button btnProcess;
    private Button btnSave;
    private SeekBar seekBarBrushSize;
    private TextView tvBrushSize;
    private ImageView btnBack;

    private Bitmap originalBitmap;
    private Bitmap resultBitmap;

    // LaMa去水印处理器
    private LamaWatermarkProcessor lamaProcessor;

    // 移除其他处理器，专门使用Big-LaMa FP16模型
    // private WatermarkRemovalProcessor watermarkRemovalProcessor;
    // private WatermarkRemovalTFLiteProcessor watermarkRemovalTFLiteProcessor;

    // 界面模式
    private enum ViewMode {
        UPLOAD,    // 上传模式
        EDIT,      // 编辑模式
        COMPARE    // 对比模式
    }

    private ViewMode currentMode = ViewMode.UPLOAD;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_watermark_removal);
        
        initViews();
        setupListeners();

        // 异步初始化Big-LaMa去水印处理器
        initLamaProcessor();
        checkPermissions();
    }
    
    private void initViews() {
        watermarkCanvas = findViewById(R.id.watermarkCanvas);
        slideCompareView = findViewById(R.id.slideCompareView);
        uploadArea = findViewById(R.id.uploadArea);
        progressOverlay = findViewById(R.id.progressOverlay);
        tvProgress = findViewById(R.id.tvProgress);
        tvProgressDetail = findViewById(R.id.tvProgressDetail);
        btnUndo = findViewById(R.id.btnUndo);
        btnRedo = findViewById(R.id.btnRedo);
        btnClear = findViewById(R.id.btnClear);
        btnProcess = findViewById(R.id.btnProcess);
        btnSave = findViewById(R.id.btnSave);
        seekBarBrushSize = findViewById(R.id.seekBarBrushSize);
        tvBrushSize = findViewById(R.id.tvBrushSize);
        btnBack = findViewById(R.id.btnBack);

        // 初始化参数
        seekBarBrushSize.setProgress(20);
        tvBrushSize.setText("画笔大小: 20px");

        // 默认显示上传模式
        switchToMode(ViewMode.UPLOAD);
    }
    
    private void setupListeners() {
        btnBack.setOnClickListener(v -> handleBackPress());
        uploadArea.setOnClickListener(v -> selectImage());
        btnUndo.setOnClickListener(v -> watermarkCanvas.undo());
        btnRedo.setOnClickListener(v -> watermarkCanvas.redo());
        btnClear.setOnClickListener(v -> watermarkCanvas.clearMask());
        btnProcess.setOnClickListener(v -> processWatermarkRemoval());
        btnSave.setOnClickListener(v -> saveResultToGallery());

        seekBarBrushSize.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                int brushSize = Math.max(5, progress);
                watermarkCanvas.setBrushSize(brushSize);
                tvBrushSize.setText("画笔大小: " + brushSize + "px");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {}
        });
    }

    /**
     * 异步初始化Big-LaMa去水印处理器
     */
    private void initLamaProcessor() {
        Log.d(TAG, "开始异步初始化Big-LaMa FP16去水印处理器...");

        new Thread(() -> {
            try {
                Log.d(TAG, "初始化Big-LaMa处理器...");

                // 显示加载提示
                runOnUiThread(() -> {
                    if (!isFinishing() && !isDestroyed()) {
                        Toast.makeText(this, "正在加载Big-LaMa模型，请稍候...", Toast.LENGTH_LONG).show();
                    }
                });

                lamaProcessor = new LamaWatermarkProcessor(this);

                if (!isFinishing() && !isDestroyed()) {
                    runOnUiThread(() -> {
                        try {
                            if (isFinishing() || isDestroyed()) {
                                Log.w(TAG, "Activity已销毁，跳过Big-LaMa初始化UI更新");
                                return;
                            }

                            if (lamaProcessor.isInitialized()) {
                                Log.d(TAG, "Big-LaMa处理器初始化成功");
                                Toast.makeText(this, "Big-LaMa去水印模型加载成功", Toast.LENGTH_SHORT).show();
                            } else {
                                Log.e(TAG, "Big-LaMa处理器初始化失败");
                                Toast.makeText(this, "Big-LaMa模型加载失败", Toast.LENGTH_SHORT).show();
                                lamaProcessor = null;
                            }
                        } catch (Exception uiException) {
                            Log.e(TAG, "Big-LaMa初始化UI更新异常", uiException);
                        }
                    });
                }

            } catch (Exception e) {
                Log.e(TAG, "Big-LaMa处理器初始化异常", e);
                if (!isFinishing() && !isDestroyed()) {
                    runOnUiThread(() -> {
                        try {
                            String errorMsg = "Big-LaMa模型加载失败";
                            String suggestion = "";

                            if (e.getMessage() != null) {
                                if (e.getMessage().contains("ONNX Runtime不可用")) {
                                    errorMsg = "ONNX Runtime库不可用";
                                    suggestion = "请检查应用依赖";
                                } else if (e.getMessage().contains("模型文件")) {
                                    errorMsg = "模型文件问题";
                                    suggestion = "请检查big-lama.onnx文件";
                                } else if (e.getMessage().contains("内存不足") || e.getMessage().contains("OutOfMemoryError")) {
                                    errorMsg = "设备内存不足";
                                    suggestion = "请关闭其他应用后重试，或重启设备";
                                } else if (e.getMessage().contains("会话创建失败")) {
                                    errorMsg = "模型加载卡住";
                                    suggestion = "200MB模型较大，请耐心等待或重启应用";
                                } else if (e.getMessage().contains("timeout") || e.getMessage().contains("超时")) {
                                    errorMsg = "模型加载超时";
                                    suggestion = "请重启应用重试，或检查设备性能";
                                } else {
                                    errorMsg = "模型加载失败";
                                    suggestion = e.getMessage();
                                }
                            }

                            String fullMessage = errorMsg;
                            if (!suggestion.isEmpty()) {
                                fullMessage += "\n建议: " + suggestion;
                            }

                            Toast.makeText(this, fullMessage, Toast.LENGTH_LONG).show();
                            lamaProcessor = null;
                        } catch (Exception uiException) {
                            Log.e(TAG, "异常处理UI更新失败", uiException);
                        }
                    });
                }
            }
        }).start();
    }

    private void handleBackPress() {
        switch (currentMode) {
            case COMPARE:
                // 从对比模式返回编辑模式
                switchToMode(ViewMode.EDIT);
                Toast.makeText(this, "返回编辑模式，可继续调整标记区域", Toast.LENGTH_SHORT).show();
                break;

            case EDIT:
                // 从编辑模式返回上传模式
                switchToMode(ViewMode.UPLOAD);
                break;

            case UPLOAD:
            default:
                // 从上传模式退出应用
                finish();
                break;
        }
    }
    
    private void checkPermissions() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    REQUEST_PERMISSION);
        }
    }
    
    private void selectImage() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
        startActivityForResult(intent, REQUEST_IMAGE_PICK);
    }
    
    private void switchToMode(ViewMode mode) {
        try {
            if (isFinishing() || isDestroyed()) {
                Log.w(TAG, "Activity已销毁，跳过模式切换");
                return;
            }

            currentMode = mode;

            // 安全地隐藏所有视图
            if (uploadArea != null) {
                uploadArea.setVisibility(View.GONE);
            }
            if (watermarkCanvas != null) {
                watermarkCanvas.setVisibility(View.GONE);
            }
            if (slideCompareView != null) {
                slideCompareView.setVisibility(View.GONE);
            }

            switch (mode) {
                case UPLOAD:
                    if (uploadArea != null) {
                        uploadArea.setVisibility(View.VISIBLE);
                    }
                    break;

                case EDIT:
                    if (watermarkCanvas != null) {
                        watermarkCanvas.setVisibility(View.VISIBLE);
                    }
                    break;

                case COMPARE:
                    if (slideCompareView != null) {
                        slideCompareView.setVisibility(View.VISIBLE);
                    }
                    break;
            }

            Log.d(TAG, "切换到模式: " + mode);
        } catch (Exception e) {
            Log.e(TAG, "切换模式异常", e);
        }
    }

    private void showProgress(String message, String detail) {
        tvProgress.setText(message);
        tvProgressDetail.setText(detail);
        progressOverlay.setVisibility(View.VISIBLE);
    }

    private void hideProgress() {
        progressOverlay.setVisibility(View.GONE);
    }
    
    private void processWatermarkRemoval() {
        // 1. 检查前置条件
        if (originalBitmap == null) {
            Toast.makeText(this, "请先选择图片", Toast.LENGTH_SHORT).show();
            return;
        }
        
        boolean hasMarkedAreas = watermarkCanvas.hasMarkedAreas();
        if (!hasMarkedAreas) {
            Toast.makeText(this, "请先标记需要去除的水印区域", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 2. 显示进度
        showProgress("正在处理中...", "准备上传图片");
        
        // 3. 生成带遮罩的图片
        Bitmap maskedImage = watermarkCanvas.generateMaskedImage();
        
        // 4. 调用后端API（带认证token）
        WatermarkRemovalAPI.removeWatermark(maskedImage, new WatermarkRemovalAPI.WatermarkRemovalCallback() {
            @Override
            public void onSuccess(Bitmap resultBitmap) {
                runOnUiThread(() -> {
                    hideProgress();
                    // 保存结果
                    WatermarkRemovalActivity.this.resultBitmap = resultBitmap;
                    // 显示对比结果
                    slideCompareView.setOriginalBitmap(originalBitmap);
                    slideCompareView.setProcessedBitmap(resultBitmap);
                    switchToMode(ViewMode.COMPARE);
                    Toast.makeText(WatermarkRemovalActivity.this, "去水印完成！滑动查看对比效果", Toast.LENGTH_LONG).show();
                });
            }
            
            @Override
            public void onError(String errorMessage) {
                runOnUiThread(() -> {
                    hideProgress();
                    Toast.makeText(WatermarkRemovalActivity.this, "去水印失败：" + errorMessage, Toast.LENGTH_LONG).show();
                });
            }
            
            @Override
            public void onProgress(String progressMessage) {
                runOnUiThread(() -> {
                    tvProgressDetail.setText(progressMessage);
                });
            }
        });
    }

    /**
     * 回退到API处理
     */
    private void fallbackToAPIProcessing(Bitmap maskedImage) {
        Log.d(TAG, "回退到API去水印处理...");
        WatermarkRemovalAPI.removeWatermark(maskedImage, new WatermarkRemovalAPI.WatermarkRemovalCallback() {
            @Override
            public void onSuccess(Bitmap resultBitmap) {
                Log.d(TAG, "=== API调用成功回调 ===");
                runOnUiThread(() -> handleWatermarkRemovalSuccess(resultBitmap, "API"));
            }

            @Override
            public void onError(String errorMessage) {
                Log.e(TAG, "=== API调用失败回调 ===");
                Log.e(TAG, "错误信息：" + errorMessage);

                runOnUiThread(() -> {
                    hideProgress();
                    Toast.makeText(WatermarkRemovalActivity.this, "去水印失败：" + errorMessage, Toast.LENGTH_LONG).show();
                });
            }

            @Override
            public void onProgress(String progressMessage) {
                Log.d(TAG, "API进度更新：" + progressMessage);

                runOnUiThread(() -> {
                    tvProgressDetail.setText(progressMessage);
                });
            }
        });
    }

    /**
     * 处理去水印成功结果
     * @param resultBitmap 处理结果图像
     * @param usedProcessor 使用的处理器名称
     */
    private void handleWatermarkRemovalSuccess(Bitmap resultBitmap, String usedProcessor) {
        try {
            if (isFinishing() || isDestroyed()) {
                Log.w(TAG, "Activity已销毁，跳过结果处理");
                if (resultBitmap != null) {
                    resultBitmap.recycle();
                }
                return;
            }

            hideProgress();

            if (resultBitmap != null) {
                Log.d(TAG, "收到处理结果图片：宽度=" + resultBitmap.getWidth() + ", 高度=" + resultBitmap.getHeight());

                // 保存结果
                WatermarkRemovalActivity.this.resultBitmap = resultBitmap;

                // 简化的对比显示
                try {
                    if (slideCompareView != null && originalBitmap != null) {
                        slideCompareView.setOriginalBitmap(originalBitmap);
                        slideCompareView.setProcessedBitmap(resultBitmap);

                        // 切换到对比模式
                        switchToMode(ViewMode.COMPARE);

                        // 显示成功消息
                        String message;
                        if ("Big-LaMa".equals(usedProcessor) && lamaProcessor != null) {
                            message = "Big-LaMa去水印完成！滑动查看对比效果\n" +
                                     "推理耗时: " + String.format("%.0f", lamaProcessor.getInferenceTime()) + "ms";
                        } else {
                            message = "Big-LaMa去水印完成！滑动查看对比效果";
                        }

                        Log.d(TAG, "=== 去水印处理流程完成 ===");
                        Toast.makeText(this, message, Toast.LENGTH_LONG).show();
                    } else {
                        Log.w(TAG, "对比视图或原图为空");
                        Toast.makeText(this, "处理完成，但无法显示对比", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception displayException) {
                    Log.e(TAG, "显示对比结果异常", displayException);
                    Toast.makeText(this, "处理完成，显示异常", Toast.LENGTH_SHORT).show();
                }
            } else {
                Log.e(TAG, "错误：处理结果图片为空");
                Toast.makeText(this, "处理结果为空", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Log.e(TAG, "处理成功结果时异常", e);
            hideProgress();
            Toast.makeText(this, "处理异常", Toast.LENGTH_SHORT).show();
        }
    }
    
    private void saveResultToGallery() {
        if (resultBitmap == null) {
            Toast.makeText(this, "请先进行去水印处理", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            // 保存到相册
            String savedImageURL = MediaStore.Images.Media.insertImage(
                    getContentResolver(),
                    resultBitmap,
                    "去水印图片_" + System.currentTimeMillis(),
                    "使用前端去水印工具处理的图片"
            );

            if (savedImageURL != null) {
                Toast.makeText(this, "✅ 图片已保存到相册", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, "❌ 保存失败，请检查存储权限", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "❌ 保存失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_IMAGE_PICK && resultCode == RESULT_OK && data != null) {
            Uri imageUri = data.getData();
            if (imageUri != null) {
                try {
                    InputStream inputStream = getContentResolver().openInputStream(imageUri);
                    Bitmap tempBitmap = BitmapFactory.decodeStream(inputStream);

                    if (tempBitmap != null) {
                        // 压缩图片以避免内存问题
                        originalBitmap = compressBitmapIfNeeded(tempBitmap);

                        // 释放临时bitmap
                        if (originalBitmap != tempBitmap) {
                            tempBitmap.recycle();
                        }

                        watermarkCanvas.setImageBitmap(originalBitmap);
                        switchToMode(ViewMode.EDIT); // 切换到编辑模式
                        Toast.makeText(this, "图片加载成功，开始标记水印区域吧！", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(this, "图片加载失败", Toast.LENGTH_SHORT).show();
                    }
                } catch (IOException e) {
                    Log.e(TAG, "加载图片失败", e);
                    Toast.makeText(this, "图片加载失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                } catch (OutOfMemoryError e) {
                    Log.e(TAG, "图片加载内存不足", e);
                    System.gc();
                    Toast.makeText(this, "图片太大，请选择较小的图片", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        
        if (requestCode == REQUEST_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "权限已授予", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "需要存储权限才能选择图片", Toast.LENGTH_SHORT).show();
            }
        }
    }
    
    @Override
    public void onBackPressed() {
        handleBackPress();
    }

    @Override
    protected void onDestroy() {
        Log.d(TAG, "Activity正在销毁，清理资源...");
        super.onDestroy();

        // 取消所有网络请求
        WatermarkRemovalAPI.cancelAllRequests();

        // 释放Big-LaMa去水印处理器资源
        if (lamaProcessor != null) {
            Log.d(TAG, "释放Big-LaMa处理器资源...");
            lamaProcessor.release();
            lamaProcessor = null;
        }

        Log.d(TAG, "Activity销毁完成");
    }

    /**
     * 创建测试图片用于演示
     */
    private Bitmap createTestImage() {
        int width = 800;
        int height = 600;
        Bitmap testBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(testBitmap);

        // 绘制渐变背景
        Paint backgroundPaint = new Paint();
        backgroundPaint.setColor(Color.parseColor("#E3F2FD"));
        canvas.drawRect(0, 0, width, height, backgroundPaint);

        // 绘制一些图形作为内容
        Paint shapePaint = new Paint();
        shapePaint.setAntiAlias(true);

        // 绘制圆形
        shapePaint.setColor(Color.parseColor("#2196F3"));
        canvas.drawCircle(200, 150, 80, shapePaint);

        // 绘制矩形
        shapePaint.setColor(Color.parseColor("#4CAF50"));
        canvas.drawRect(400, 100, 600, 200, shapePaint);

        // 绘制文字
        Paint textPaint = new Paint();
        textPaint.setColor(Color.parseColor("#333333"));
        textPaint.setTextSize(48);
        textPaint.setAntiAlias(true);
        canvas.drawText("测试图片", 300, 350, textPaint);

        // 绘制模拟水印
        Paint watermarkPaint = new Paint();
        watermarkPaint.setColor(Color.parseColor("#FF5722"));
        watermarkPaint.setTextSize(36);
        watermarkPaint.setAntiAlias(true);
        canvas.drawText("WATERMARK", 250, 450, watermarkPaint);

        Log.d(TAG, "创建测试图片: " + width + "x" + height);
        return testBitmap;
    }

    /**
     * 压缩图片以避免内存问题
     */
    private Bitmap compressBitmapIfNeeded(Bitmap bitmap) {
        if (bitmap == null) return null;

        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        // 设置最大尺寸限制（避免内存溢出）
        final int MAX_SIZE = 2048;

        if (width <= MAX_SIZE && height <= MAX_SIZE) {
            Log.d(TAG, "图片尺寸合适，无需压缩");
            return bitmap;
        }

        // 计算压缩比例
        float scale = Math.min((float) MAX_SIZE / width, (float) MAX_SIZE / height);
        int newWidth = (int) (width * scale);
        int newHeight = (int) (height * scale);

        Log.d(TAG, "压缩图片：" + width + "x" + height + " -> " + newWidth + "x" + newHeight);

        try {
            Bitmap compressedBitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
            return compressedBitmap;
        } catch (OutOfMemoryError e) {
            Log.e(TAG, "压缩图片时内存不足", e);
            System.gc();
            return bitmap; // 返回原图片
        }
    }


}
